package com.ybbase.framework.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ybbase.framework.common.constant.ConfigConstant;
import com.ybbase.framework.common.util.ArrayUtil;
import com.ybbase.framework.config.shiro.JwtUtils;
import com.ybbase.framework.mapper.system.*;
import com.ybbase.framework.model.po.system.*;
import com.ybbase.framework.service.system.OrganizationService;
import com.ybbase.framework.service.system.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author cg
 * @since 2019-11-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    AnnexMapper annexMapper;
    @Autowired
    OrganizationService organizationService;
    @Autowired
    OrganizationMapper organizationMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    OrganUserMapper organUserMapper;
    @Autowired
    RolePermissionMapper rolePermissionMapper;
    @Autowired
    UserPermissionMapper userPermissionMapper;
    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 生成用户JwtToken
     *
     * @param userId 用户编码
     * @return String
     * @author cg
     * @date 2019-11-26 16:18
     * @since cloud2.0
     */
    @Override
    public String generateJwtToken(Integer userId) {
        User user = userMapper.selectById(userId);
        Annex annex = annexMapper.selectById(user.getIcon() > 0 ? user.getIcon() : 0);
        if (annex != null) {
            user.setIconPath(annex.getPath());
        }
        List<Organization> orgList = organizationMapper.getOrgListByUserId(userId);
        Organization org = new Organization();
        if (orgList != null && orgList.size() > 0) {
            org = orgList.get(0);
        }
        return JwtUtils.sign(user, ConfigConstant.TOKEN_SALT, org, ConfigConstant.TOKEN_EXPIRE_DATE);
    }

    /**
     * 根据登录名称获取用户信息
     *
     * @param loginName 登录名称
     * @return User
     * @author cg
     * @date 2019-11-27 11:49
     * @since cloud2.0
     */
    @Override
    public User getUserByLoginName(String loginName) {
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.lambda().eq(User::getLoginName, loginName);
        return userMapper.selectOne(userQuery);
    }

    /**
     * 获取用户全部信息
     *
     * @param userId 用户编码
     * @return User
     * @author cg
     * @date 2019-11-28 10:25
     * @since cloud2.0
     */
    @Override
    public User getUserAllInfo(Integer userId) {
        User user = userMapper.selectById(userId);
        if (user != null) {
            user.setOrganCompany(organizationService.getOrganCompanyByUserId(userId));
            user.setOrganizationList(organizationMapper.getOrgListByUserId(userId));
            user.setRoleList(roleMapper.getRoleListByUserId(userId));
            List<OrganUser> list = getOrganUserList(userId);
            user.setOrganUserList(list);
            if (list != null && !list.isEmpty()) {
                user.setDefaultOrgId(list.get(0).getOrgId());
            }
            //Annex annex = annexMapper.selectById(user.getIcon()>0 ? user.getIcon() : 0);
            //if (annex != null) {
            //    user.setIconPath(annex.getPath());
            //}
        }
        return user;
    }

    /**
     * 根据用户Id获取用户组织机构
     *
     * @param userId 用户编码
     * @return List<OrganUser>
     * @author cg
     * @date 2019-11-28 16:44
     * @since cloud2.0
     */
    @Override
    public List<OrganUser> getOrganUserList(Integer userId) {
        QueryWrapper<OrganUser> organUserQueryWrapper = new QueryWrapper<>();
        organUserQueryWrapper.lambda().eq(OrganUser::getUserId, userId);
        return organUserMapper.selectList(organUserQueryWrapper);
    }

    /**
     * 根据用户Id获取用户组织机构
     *
     * @param userId  用户编码
     * @param organId 组织机构编码
     * @return List<OrganUser>
     * @author cg
     * @date 2019-11-28 16:44
     * @since cloud2.0
     */
    @Override
    public List<OrganUser> getOrganUserList(Integer userId, Integer organId) {
        QueryWrapper<OrganUser> organUserQueryWrapper = new QueryWrapper<>();
        organUserQueryWrapper.lambda().eq(OrganUser::getUserId, userId);
        organUserQueryWrapper.lambda().eq(OrganUser::getOrgId, organId);
        return organUserMapper.selectList(organUserQueryWrapper);
    }

    /**
     * 保存用户信息
     *
     * @param user 用户信息
     * @author cg
     * @date 2019-11-28 17:37
     * @since cloud2.0
     */
    @Override
    public void saveUser(User user) {
        if (user.getId() != null && user.getId() > 0) {
            userMapper.updateById(user);
        } else {
            userMapper.insert(user);
        }
        saveUserRole(user.getId(), user.getRoleList());
        saveUserOrgan(user.getDefaultOrgId(), user.getId());
        saveUserPermission(user);
    }

    /**
     * 保存用户权限
     * @param
     * @return
     * @author cg
     * @date 2020-03-27 23:07
     * @since cloud2.0
    */
    private void saveUserPermission(User user) {
        UpdateWrapper<UserPermission> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(UserPermission::getUserId, user.getId());
        userPermissionMapper.delete(updateWrapper);
        String roleStr = "";
        if(user.getRoleList()!=null&&!user.getRoleList().isEmpty()){
            for(Role role:user.getRoleList()){
                roleStr = StringUtils.isNotEmpty(roleStr)?roleStr+","+role.getId():role.getId()+"";
            }
        }
        List<Permission> list =permissionMapper.getPermissionByIdsCg(roleStr.split(","));
        for (Permission keycg:list){
            UserPermission userPermission = new UserPermission();
            userPermission.setUserId(user.getId());
            userPermission.setPerId(keycg.getId());
            userPermission.setDataScope(Integer.parseInt(keycg.getDataScope()));
            userPermission.setDataMethod(keycg.getPermission());
            userPermissionMapper.insert(userPermission);
        }

    }

    /**
     * 保存用户角色
     *
     * @param userId  用户编码
     * @param roleIds 角色编码
     * @author cg
     * @date 2019-11-28 10:47
     * @since cloud2.0
     */
    @Override
    public void saveUserRole(Integer userId, List<Role> roleIds) {
        /**
         * 删除用户已经存在的角色
         * */
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserRole::getUserId, userId);
        userRoleMapper.delete(queryWrapper);
        /**
         * 重新增加用户角色信息
         * */
        if (roleIds != null && roleIds.size() > 0) {
            for (Role role : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(role.getId());
                userRole.setUserId(userId);
                userRoleMapper.insert(userRole);
            }
        }
    }


    /**
     * 保存用户机构和岗位信息
     *
     * @param organId 组织机构编码
     * @param userId  用户编码
     * @author cg
     * @date 2019-11-28 16:16
     * @since cloud2.0
     */
    @Override
    public void saveUserOrgan(Integer organId, Integer userId) {
        UpdateWrapper<OrganUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(OrganUser::getUserId, userId);
        organUserMapper.delete(updateWrapper);
        OrganUser organUser = new OrganUser();
        organUser.setOrgId(organId);
        organUser.setUserId(userId);
        organUserMapper.insert(organUser);
    }

    /**
     * 删除用户的组织机构关联
     *
     * @param userId  用户编码
     * @param organId 组织机构编码
     * @author cg
     * @date 2019-11-28 16:31
     * @since cloud2.0
     */
    @Override
    public void deleteUserOrgan(Integer userId, Integer organId) {
        QueryWrapper<OrganUser> organUserQueryWrapper = new QueryWrapper<>();
        organUserQueryWrapper.lambda().eq(OrganUser::getUserId, userId);
        organUserQueryWrapper.lambda().eq(OrganUser::getOrgId, organId);
        organUserMapper.delete(organUserQueryWrapper);
    }

    /**
     * 根据组织机构获取用户列表
     *
     * @param organId@return
     * @author cg
     * @date 2020-01-11 12:07
     * @since cloud2.0
     */
    @Override
    public List<User> getUserListByOrgId(String organId) {
        return userMapper.getUserListByOrgId(organId);
    }

    /**
     * 根据角色ID获取下面所有的用户
     *
     * @param pageIndex
     * @param step
     * @param id
     * @return
     * @date 2020年3月2日12:23:10
     * @author phm
     */
    @Override
    public IPage<User> getUserByRoleId(IPage<User> page, QueryWrapper<User> queryWrapper, Integer[] id, String name) {
        return userMapper.getUserByRoleId(page, queryWrapper, id, name);
    }

    /**
     * 根据用户ID获取相关数据
     *
     * @param userId 用户编码
     * @return
     * @author cg
     * @date 2020-03-29 17:58
     * @since cloud2.0
     */
    @Override
    public User getScopeById(int userId) {
        User user = userMapper.selectById(userId);
        List<Role> list = roleMapper.getRoleListByUserId(userId);
        String roleNames = "";
        String roleIds = "";
        if (list!=null&&!list.isEmpty()){
            for(Role role:list){
                roleIds = StringUtils.isNotEmpty(roleIds)?roleIds+","+role.getId():role.getId()+"";
                roleNames = StringUtils.isNotEmpty(roleNames)?roleNames+","+role.getName():role.getName();
            }
        }
        user.setRoleIds(roleIds);
        user.setRoleNames(roleNames);
        return user;
    }

}
